package qier

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	"publish/pub-lib/baijia"
	"publish/pub-lib/utils"
	"github.com/astaxie/beego"
)

func (q *QierApi) PublishArticle1(cat string, tag string, article baijia.FeedArticle) error {
	catId, ok := CatNameToID(cat)
	if !ok {
		return errors.New("没找到企鹅分类ID：" + cat)
	}

	qa := &QArticle{}
	qa.Cat = catId
	qa.CoverType = "3"
	qa.Title = article.Title
	covers := []map[string]string{}
	imageIndex := 0
	var defaultCover map[string]string

	for _, feed := range article.Feed {
		if feed.Type == "image" {
			urlRes, err := q.UploadImageByUrl(feed.Data)
			if err != nil {
				beego.Error("图片上传失败：", err.Error())
				continue
			}
			qa.Content += Imgwrapper(urlRes.Url, urlRes.Srcurl)

			if defaultCover == nil {
				cover, err := q.UploadCoverImage(urlRes.Url)
				if err != nil {
					beego.Error("图片裁剪失败：", err.Error())
					continue
				}
				defaultCover = cover.Data
			}
			beego.Info("图片上传成功:", urlRes.Url)
		}

		if feed.Type == "cover" {
			urlRes, err := q.UploadImageByUrl(feed.Data)
			if err != nil {
				beego.Error("图片上传失败：", err.Error())
				continue
			}
			qa.Content += Imgwrapper(urlRes.Url, urlRes.Srcurl)
			if imageIndex < 3 {
				cover, err := q.UploadCoverImage(urlRes.Url)
				if err != nil {
					beego.Error("图片裁剪失败：", err.Error())
					continue
				}
				covers = append(covers, cover.Data)
				imageIndex++
			}
			beego.Info("图片上传成功:", urlRes.Url)
		}

		if feed.Type == "text" {
			qa.Content += Pwrapper(feed.Data)
		}
	}

	if len(covers) == 0 {
		covers = append(covers, defaultCover)
		qa.CoverType = "1"
	}

	if len(covers) == 1 {
		qa.CoverType = "1"
	}

	coverBytes, err := json.Marshal(covers)
	if err != nil {
		return err
	}
	qa.CoverImage = string(coverBytes)
	fmt.Println("Cover:", qa.CoverImage)
	fmt.Println("正在发布:", qa)
	return q.publish(qa)
}

func (q *QierApi) PublishArticle(cat string, tag string, article baijia.FeedArticle) error {
	catId, ok := CatNameToID(cat)
	if !ok {
		return errors.New("没找到企鹅分类ID：" + cat)
	}

	qa := &QArticle{
		Cat:       catId,
		CoverType: "3",
		Title:     article.Title,
	}

	defaultCover := ""
	imageUrls := []string{}
	coverUrls := []string{}
	coverList := []map[string]string{}

	// 取出所有图片和封面
	for _, feed := range article.Feed {
		if feed.Type == "image" || feed.Type == "cover" {
			imageUrls = append(imageUrls, feed.Data)
			if defaultCover == "" {
				defaultCover = feed.Data
			}
		}
		if feed.Type == "cover" {
			coverUrls = append(coverUrls, feed.Data)
		}
	}

	//上传所有图片
	images, err := q.UploadImageByUrlAll(strings.Join(imageUrls, ","))
	if err != nil {
		beego.Error("图片上传失败：", err.Error())
		return nil
	}
	beego.Error("图片上传成功.")

	fmt.Println("images:", images)
	fmt.Println("coverUrls:", coverUrls)

	if len(coverUrls) == 0 {
		urlres, ok := images[defaultCover]
		if !ok {
			return errors.New("获取封面失败")
		}
		fmt.Println(urlres.Url)
		coverImage, err := q.UploadCoverImage(urlres.Url)
		if err != nil {
			return errors.New("封面裁剪失败：" + err.Error())
		}
		beego.Error("封面上传成功")

		coverList = append(coverList, coverImage.Data)
	} else {
		//剪切所有封面
		for _, coverUrl := range coverUrls {
			urlres, ok := images[coverUrl]
			if !ok {
				continue
			}
			coverImage, err := q.UploadCoverImage(urlres.Url)
			if err != nil {
				beego.Error("封面裁剪失败：", err.Error())
				continue
			}
			beego.Error("封面上传成功")

			coverList = append(coverList, coverImage.Data)
		}
	}

	// 拼接html
	for _, feed := range article.Feed {
		if feed.Type == "image" || feed.Type == "cover" {
			urlres, ok := images[feed.Data]
			if !ok {
				continue
			}
			qa.Content += Imgwrapper(urlres.Url, urlres.Srcurl)
		}

		if feed.Type == "text" {
			qa.Content += Pwrapper(feed.Data)
		}
	}

	// 处理封面缺失
	if len(coverList) == 1 {
		qa.CoverType = "1"
	}

	coverBytes, err := json.Marshal(coverList)
	if err != nil {
		return err
	}
	qa.CoverImage = string(coverBytes)
	fmt.Println("Cover:", qa.CoverImage)
	fmt.Println("正在发布:", qa)
	return q.publish(qa)
}

func (q *QierApi) PublishGallery(cat string, tag string, article baijia.FeedArticle) error {
	catId, ok := CatNameToID(cat)
	if !ok {
		return errors.New("没找到企鹅分类ID：" + cat)
	}

	qa := &QArticle{}
	qa.Cat = catId
	qa.Title = article.Title
	covers := []map[string]string{}
	contents := []GalleryContent{}
	var defaultCover map[string]string
	imageIndex := 0
	for _, feed := range article.Feed {
		if feed.Type == "image" || feed.Type == "cover" {
			urlRes, err := q.UploadImageByUrl(feed.Data)
			if err != nil {
				beego.Error("图片上传失败：", err.Error())
				continue
			}
			contents = append(contents, GalleryContent{Image: urlRes.Url, Desc: feed.Desc})
			// qa.Content += Imgwrapper(urlRes.Url, urlRes.Srcurl)

			if defaultCover == nil || (imageIndex < 3 && feed.Type == "cover") {
				cover, err := q.UploadCoverImage(urlRes.Url)
				if err != nil {
					beego.Error("图片裁剪失败：", err.Error())
					continue
				}

				if defaultCover == nil {
					defaultCover = cover.Data
				}

				if imageIndex < 3 && feed.Type == "cover" {
					covers = append(covers, cover.Data)
					imageIndex++
				}
			}
		}

		// if feed.Type == "cover" {
		// 	urlRes, err := q.UploadImageByUrl(feed.Data)
		// 	if err != nil {
		// 		beego.Error("图片上传失败：", err.Error())
		// 		continue
		// 	}

		// 	contents = append(contents, GalleryContent{Image: urlRes.Url, Desc: feed.Desc})

		// 	if imageIndex < 3 {
		// 		cover, err := q.UploadCoverImage(urlRes.Url)
		// 		if err != nil {
		// 			beego.Error("图片裁剪失败：", err.Error())
		// 			continue
		// 		}
		// 		covers = append(covers, cover.Data)
		// 		imageIndex++
		// 	}
		// 	beego.Info("图片上传成功:", urlRes.Url)
		// }
	}
	if len(covers) <= 0 && defaultCover != nil {
		covers = append(covers, defaultCover)
	}

	if len(covers) <= 0 {
		return errors.New("封面图为空")
	}

	if len(covers) < 3 {
		qa.CoverImage = "1"
		covers = covers[:1]
	} else {
		qa.CoverImage = "3"
		covers = covers[:3]
	}

	coverBytes, err := json.Marshal(covers)
	if err != nil {
		return err
	}
	qa.CoverImage = string(coverBytes)

	contentsBytes, err := json.Marshal(contents)
	if err != nil {
		return err
	}
	qa.Content = string(contentsBytes)

	return q.publishGallery(qa)
}

func (p *QierApi) PublishVideo(cat string, tag string, feeds baijia.FeedArticle) error {
	videoPath := ""
	imagePath := ""
	desc := ""
	for _, feed := range feeds.Feed {
		if feed.Type == "video" {
			videoPath = feed.Data
			desc = feed.Desc
		}
		if feed.Type == "cover" {
			imagePath = feed.Data
		}
	}

	if utils.TitleCount(feeds.Title, true) > 30 {
		return errors.New("标题长度大于30")
	}

	return PubVideo(p.ck, cat, videoPath, imagePath, feeds.Title, desc, tag)
}
